// Copyright (c) 2022 by Duguang.IO Inc. All Rights Reserved.
// Author: Ethan Liu
// Date: 2022-05-05 12:42:57
// LastEditors: Please set LastEditors

package engine

import (
	"bytes"
	"encoding/json"
)

// PullPolicy 定义容器镜像拉取策略
type PullPolicy int

// PullPolicy 枚举.
const (
	PullDefault PullPolicy = iota
	PullAlways
	PullIfNotExists
	PullNever
)

func (p PullPolicy) String() string {
	return pullPolicyID[p]
}

var pullPolicyID = map[PullPolicy]string{
	PullDefault:     "default",
	PullAlways:      "always",
	PullIfNotExists: "if-not-exists",
	PullNever:       "never",
}

var pullPolicyName = map[string]PullPolicy{
	"":              PullDefault,
	"default":       PullDefault,
	"always":        PullAlways,
	"if-not-exists": PullIfNotExists,
	"never":         PullNever,
}

// MarshalJSON marshals 将PullPolicy序列化为字符串
func (p *PullPolicy) MarshalJSON() ([]byte, error) {
	buffer := bytes.NewBufferString(`"`)
	buffer.WriteString(pullPolicyID[*p])
	buffer.WriteString(`"`)
	return buffer.Bytes(), nil
}

// UnmarshalJSON 将字符串反序列化为PullPolicy类型
func (p *PullPolicy) UnmarshalJSON(b []byte) error {
	// 反序列化字符串
	var s string
	err := json.Unmarshal(b, &s)
	if err != nil {
		return err
	}
	// 查找对应的值
	*p = pullPolicyName[s]
	return nil
}

type TaskStatus int

// TaskStatus 枚举定义
const (
	Running TaskStatus = iota
	Succeed
	Failed
)

func (s TaskStatus) String() string {
	return taskStatusID[s]
}

var taskStatusID = map[TaskStatus]string{
	Running: "RUNNING",
	Succeed: "SUCCEED",
	Failed:  "FAILED",
}

var TaskStatusName = map[string]TaskStatus{
	"RUNNING": Running,
	"SUCCEED": Succeed,
	"FAILED":  Failed,
}

// MarshalJSON 将TaskStatus序列化为字符串
func (s *TaskStatus) MarshalJSON() ([]byte, error) {
	buffer := bytes.NewBufferString(`"`)
	buffer.WriteString(taskStatusID[*s])
	buffer.WriteString(`"`)
	return buffer.Bytes(), nil
}

// UnmarshalJSON 将字符串反序列化为TaskStatus类型
func (s *TaskStatus) UnmarshalJSON(b []byte) error {
	// 反序列化字符串
	var ss string
	err := json.Unmarshal(b, &ss)
	if err != nil {
		return err
	}
	// 查找对应的值
	*s = TaskStatusName[ss]
	return nil
}
